﻿#include <QDebug>
#include <QSize>
#include <QVariant>

#include <include/cef_browser.h>
#include <include/cef_client.h>

#include "CefWebEngineCore/CefWebEngine.h"
#include "CefWebEngineCore/CefWebEnginePage.h"

class CefWebEnginePagePrivate
{
    Q_DECLARE_PUBLIC(CefWebEnginePage);

public:
    CefWebEnginePagePrivate(CefWebEnginePage *q);

    CefWebEnginePage *q_ptr;
    CefRefPtr<CefBrowser> mbrowser;
    QUrl murl;
    QSize mviewSize;
    QString mtitle;
};

CefWebEnginePagePrivate::CefWebEnginePagePrivate(CefWebEnginePage *q)
    : q_ptr(q),
    mtitle("页面")
{
}


CefWebEnginePage::CefWebEnginePage(QObject *parent)
    : QObject(parent),
    d_ptr(new CefWebEnginePagePrivate(this))
{
}

CefWebEnginePage::~CefWebEnginePage()
{
    Q_D(CefWebEnginePage);
    if (d->mbrowser)
    {
        d->mbrowser->StopLoad();
        d->mbrowser->GetHost()->CloseBrowser(true);
        d->mbrowser = nullptr;
    }
}

void CefWebEnginePage::setBrowser(void *browser)
{
    Q_D(CefWebEnginePage);
    d->mbrowser = reinterpret_cast<CefBrowser *>(browser);
    resize(size());
    reload();
}

void *CefWebEnginePage::browser() const
{
    Q_D(const CefWebEnginePage); 
    return d->mbrowser.get();
}

bool CefWebEnginePage::hasBrowser() const
{
    Q_D(const CefWebEnginePage); 
    return d->mbrowser != nullptr;
}

void CefWebEnginePage::load(const QUrl &url)
{
    Q_D(CefWebEnginePage);
    d->murl = url;
    if (d->mbrowser && !url.isEmpty())
        d->mbrowser->GetMainFrame()->LoadURL(url.toString().toStdString());
}

void CefWebEnginePage::reload()
{
    Q_D(CefWebEnginePage);
    load(d->murl);
}

QUrl CefWebEnginePage::url() const
{
    Q_D(const CefWebEnginePage);
    return d->murl;
}

void CefWebEnginePage::resize(const QSize &size)
{
    Q_D(CefWebEnginePage);
    d->mviewSize = size;
    if (!d->mbrowser)
        return;
    ::SetWindowPos(d->mbrowser->GetHost()->GetWindowHandle(),
        nullptr, 0, 0, size.width(), size.height(), SWP_NOZORDER | SWP_NOMOVE);
    d->mbrowser->GetHost()->WasResized();
}

QSize CefWebEnginePage::size() const
{
    Q_D(const CefWebEnginePage);
    return d->mviewSize;
}

void CefWebEnginePage::setTitle(const QString &title)
{
    Q_D(CefWebEnginePage);
    d->mtitle = title;
    emit titleChanged(title);
}

QString CefWebEnginePage::title() const
{
    Q_D(const CefWebEnginePage);
    return d->mtitle;
}

void CefWebEnginePage::setDevToolsPage(CefWebEnginePage *page)
{
    Q_D(CefWebEnginePage);
    if (!d->mbrowser)
        return;
    CefWebEngine::instance()->setDevToolsPage(this, page);
}
